import pyglet

import cocos
from cocos.director import director
from cocos.actions import *
from gamelib.options import options
from gamelib import items, music, ui
from random import randint

class ShoppingLayer(ui.Root):
    def __init__(self, party):
        super(ShoppingLayer, self).__init__(style=options.style)
        self.party = party
        self.shop_items = items.random_shop(party)

        # make the background a little nicer
        self.background = ui.RepeatedTileRect('canvas-bg.png',
            self._x, self._y, self._width, self._height, self.batch)

    def add_heading(self, text, x, y):
        return self.add_label(text, x, y, True)

    def add_label(self, text, x, y, bold=False):
        ui.Text(text, x=x, y=y)

    def on_enter(self):
        super(ShoppingLayer, self).on_enter()

        self.music_player = music.play('music_town_t.ogg')

        w, h = director.get_window_size()
        r = ui.Row(self)

        # display the items, sorting into duplicates
        c = ui.Column(r, width=w//2, on_drop=self.drop_shop, id='shop')
        ui.Text(c, 'Shop Items', bold=True)
        l = items.count_duplicates(self.shop_items)
        for item, count in l:
            t = ui.Text(c, '%d x %s - %d gold'%(count, item.label, item.cost),
                on_drag=ui.generic_drag_text(item.label))
            t._item = item
            t._count = count
            t._cost = item.cost

        # party items appear in the second column
        c = ui.Column(r, width=w//2, on_drop=self.drop_party, id='party')
        ui.Text(c, 'Party Items', bold=True)
        ui.Text(c, '%d gold coins'%self.party.coins, id='coins')

        # display the items, sorting into duplicates
        l = items.count_duplicates(self.party.items)
        self.party_labels = []
        for item, count in l:
            t = ui.Text(c, '%d x %s - %d gold'%(count, item.label, item.cost),
                on_drag=ui.generic_drag_text(item.label))
            t._item = item
            t._count = count
            t._cost = item.cost

        #self.add_heading('Hints:', w//4, h//4)
        #self.add_label('Drag and drop items to move them around (buy/sell).', w//4, y)
        #self.add_label('Press <esc> when you are finished.', w//4, y)

    def on_exit(self):
        self.party_labels = None
        self.shop_labels = None
        super(ShoppingLayer, self).on_exit()

        self.music_player.pause()
        self.music_player = None

    def drop_shop(self, widget, dropped):
        if dropped.parent_widget.id == 'shop': return
        item = self.remove_from_party(dropped._item)
        self.add_to_shop(item)

    def drop_party(self, widget, dropped):
        if dropped.parent_widget.id == 'party': return
        item = self.remove_from_shop(dropped._item)
        if item is not None:
            self.add_to_party(item)

    def add_to_shop(self, item):
        shop = self.by_id['shop']
        for label in shop:
            if item == getattr(label, '_item', None):
                # found existing item
                label._count += 1
                label.text = '%d x %s - %s gold'%(label._count, item.label, label._cost)
                return

        # add new item
        t = ui.Label(shop, text='1 x %s - %s gold'%(item.label, item.cost),
            on_drag=ui.generic_drag_text(item.label))
        t._item = item
        t._count = 1
        t._cost = item.cost

        self.shop_items.append(item)

    def remove_from_shop(self, item):
        coins = self.by_id['coins']
        if self.party.coins < item.cost:
            red = CallFunc(lambda: coins.set_color((255, 0, 0, 255)))
            blank = CallFunc(lambda: coins.set_color((255, 255, 255, 255)))
            black = CallFunc(lambda: coins.set_color((0, 0, 0, 255)))
            self.do((red + Delay(0.2) + blank + Delay(0.2))*5 + black)
            return None

        self.party.coins -= item.cost
        coins.text = '%d gold coins'%(self.party.coins)

        shop = self.by_id['shop']
        for label in shop:
            if getattr(label, '_item', None) == item:
                label._count -= 1
                if label._count > 0:
                    label.text = '%d x %s - %s gold'%(label._count, item.label, label._cost)
                else:
                    label.delete()
                # might not be precisely the same object
                item = label._item
                break

        self.shop_items.remove(item)
        return item

    def add_to_party(self, item):
        party = self.by_id['party']
        for label in party:
            if item == getattr(label, '_item', None):
                # found existing item
                label._count += 1
                label.text = '%d x %s - %s gold'%(label._count, item.label, label._cost)
                return

        # add new item
        t = ui.Label(party, text='1 x %s - %s gold'%(item.label, item.cost),
            on_drag=ui.generic_drag_text(item.label))
        t._item = item
        t._count = 1
        t._cost = item.cost

        self.party.items.append(item)

    def remove_from_party(self, item):
        coins = self.by_id['coins']
        self.party.coins += item.cost
        coins.text = '%d gold coins'%(self.party.coins)

        party = self.by_id['party']
        for label in party:
            if getattr(label, '_item', None) == item:
                label._count -= 1
                if label._count > 0:
                    label.text = '%d x %s - %s gold'%(label._count, item.label, label._cost)
                else:
                    label.delete()
                # might not be precisely the same object
                item = label._item
                break
        self.party.items.remove(item)
        return item

